package com.myTest.mvcFramework.servlet;

import com.myTest.demo.Handler;
import com.myTest.mvcFramework.annotations.*;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WskDispatcherServlet extends HttpServlet {
    //存储配置文件
    private Properties properties = new Properties();
    //缓存扫描到的全限定类名
    private List<String> classNames = new ArrayList<String>();

    private Map<String,Object> ioc = new HashMap<String,Object>();

    private  List<Handler> handlerMapping = new ArrayList<>();
    @Override
    public void init(ServletConfig config) throws ServletException {
        //1 加载配置文佳
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        //2 扫描注解
        String scanPackage = properties.getProperty("scanPackage");
        doScan(scanPackage);

        //3 ioc容器初始化
        doInstance();

        //4 依赖注入
        doAutowired();

        //5  springmvc 初始化
        initHandlerMapping();

        System.out.println("springmvc 初始化完成...");

        //等待请求

    }

    /*
        构造⼀个HandlerMapping处理器映射器
        最关键的环节
        ⽬的：将url和method建⽴关联
    */
    private void initHandlerMapping() {
        if(ioc.isEmpty()){return;}
        for (Map.Entry<String,Object> entry:ioc.entrySet()){
            // 获取ioc中当前遍历的对象的class类型
            Class<?> aClass = entry.getValue().getClass();

            //判断是否Controller类
            if(!aClass.isAnnotationPresent(WskController.class)){continue;}

            String baseUrl="";
            if(aClass.isAnnotationPresent(WskRequestMapping.class)){
                WskRequestMapping annotation = aClass.getAnnotation(WskRequestMapping.class);
                baseUrl = annotation.value();//相当于/demo
            }

            //判断Controller类上是否标识注解@WskSecurity
            String[] securitysValues = {};
            if(aClass.isAnnotationPresent(WskSecurity.class)){
                WskSecurity annotation = aClass.getAnnotation(WskSecurity.class);
                securitysValues = annotation.value();
            }

            //遍历方法
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                // ⽅法没有标识LagouRequestMapping，就不处理
                if(!method.isAnnotationPresent(WskRequestMapping.class)){continue;}

                // 如果标识，就处理
                WskRequestMapping annotation = method.getAnnotation(WskRequestMapping.class);
                String methodUrl = annotation.value();//相当于/query
                //组成url
                String url = baseUrl+methodUrl;

                // 把method所有信息及url封装为⼀个Handler
                Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));

                if(securitysValues.length>0){
                    handler.setSecurity(securitysValues);
                }

                if (method.isAnnotationPresent(WskSecurity.class)){
                    WskSecurity securityAnnotation = method.getAnnotation(WskSecurity.class);
                    String[] values = securityAnnotation.value();
                    if(values.length>0){
                        handler.setSecurity(values);
                    }
                }

                // 计算⽅法的参数位置信息 // query(HttpServletRequest request, HttpServletResponse response,String name)
                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {
                    Parameter parameter = parameters[j];

                    if(parameter.getType()==HttpServletRequest.class||parameter.getType()==HttpServletResponse.class){
                        // 如果是request和response对象，那么参数名称写HttpServletRequest和HttpServletResponse
                        handler.getParamterMapping().put(parameter.getType().getSimpleName(),j);
                    }else {
                        handler.getParamterMapping().put(parameter.getName(),j);
                    }
                }
                // 建⽴url和method之间的映射关系（map缓存起来）
                handlerMapping.add(handler);
            }
        }
    }

    //4 依赖注入
    private void doAutowired() {
        if(ioc.size()==0){return;}
        // 有对象，再进⾏依赖注⼊处理
        // 遍历ioc中所有对象，查看对象中的字段，是否有@LagouAutowired注解，如果有需要维护依赖注⼊关系
        for (Map.Entry<String,Object> entry:ioc.entrySet()){
            // 获取bean对象中的字段信息
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            // 遍历判断处理
            for (int i = 0; i < declaredFields.length; i++) {
                Field field = declaredFields[i];
               // @WskAutowired private IDemoService demoService;
                if(!field.isAnnotationPresent(WskAutowired.class)){
                    continue;
                }
                // 有该注解
                WskAutowired wskAutowired = field.getAnnotation(WskAutowired.class);
                String beanName = wskAutowired.value(); // 需要注⼊的bean的id
                if("".equals(beanName.trim())){
                    // 没有配置具体的bean id，那就需要根据当前字段类型注⼊（接⼝注⼊） IDemoServic
                    beanName = field.getType().getName();
                }

                // 开启赋值
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //ioc容器
    private void doInstance() {
        if(classNames.size()==0){return;}
        try {
            for (int i = 0; i < classNames.size(); i++) {
                String className = classNames.get(i);
                //反射实例化
                Class<?> aClass = Class.forName(className);
                // 区分controller，区分service'
                if(aClass.isAnnotationPresent(WskController.class)){
                // controller的id此处不做过多处理，不取value了，就拿类的⾸字⺟⼩写作为id，保存到ioc中
                    String simpleName = aClass.getSimpleName();
                    String lowerFirstName = lowerFirst(simpleName);
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstName,o);
                }else if(aClass.isAnnotationPresent(WskService.class)){
                    WskService wskService = aClass.getAnnotation(WskService.class);
                    //获取注解value值
                    String beanName = wskService.value();
                    // 如果指定了id，就以指定的为准
                    if(!"".equals(beanName.trim())){
                        ioc.put(beanName,aClass.newInstance());
                    }else {
                        // 如果没有指定，就以类名⾸字⺟⼩写
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName,aClass.newInstance());
                    }
                    // service层往往是有接⼝的，⾯向接⼝开发，此时再以接⼝名为id，放⼊⼀份对象到ioc中，便于后期根据接⼝类型注⼊
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        // 以接⼝的全限定类名作为id放⼊
                        ioc.put(anInterface.getName(),aClass.newInstance());
                    }
                }else {
                    continue;
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //首字母小写
    public String lowerFirst(String simpleName){
        char[] chars = simpleName.toCharArray();
        if('A'<=chars[0]&&chars[0]<='Z'){
            chars[0]+=32;
        }
        return String.valueOf(chars);
    }


    //扫描注解 得到磁盘路径
    private void doScan(String scanPackage) {
        //磁盘路径+com/myTest/demo
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        //根据路径得到该路径下的所有资源
        File[] files = new File(scanPackagePath).listFiles();
        for (File file : files) {
            //判断资源如果是目录则进入递归查找
            if(file.isDirectory()){
                //递归 传入com.myTest.demo.controller
                doScan(scanPackage+"."+file.getName());
            }else if(file.getName().endsWith(".class")){
                //得到全限定类名com.myTest.demo.controller.DemoController 并存储到list集合
                String className = scanPackage+"."+file.getName().replaceAll(".class","");
                classNames.add(className);
            }
        }
    }

    //加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求

        // 根据uri获取到能够处理当前请求的hanlder（从handlermapping中（list））
        Handler handler = getHandler(req);
        if (handler==null){
            resp.getWriter().write("404 not found");
            return;
        }

        String username = req.getParameter("username");
        String[] securitys = handler.getSecurity();
        if(securitys.length>0&&!Arrays.asList(securitys).contains(username)){
            resp.getWriter().write("403 No Access");
            resp.setStatus(403);
            return;
        }

        // 参数绑定
        // 获取所有参数类型数组，这个数组的⻓度就是我们最后要传⼊的args数组的⻓度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();

        // 根据上述数组⻓度创建⼀个新的数组（参数数组，是要传⼊反射调⽤的）
        Object[] paraValues = new Object[parameterTypes.length];

        // 以下就是为了向参数数组中塞值，⽽且还得保证参数的顺序和⽅法中形参顺序⼀致
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 遍历request中所有参数 （填充除了request，response之外的参数）
        for (Map.Entry<String,String[]> param: parameterMap.entrySet()){
            // name=1&name=2 name [1,2]
            String value = StringUtils.join(param.getValue(), ",");

            // 如果参数和⽅法中的参数匹配上了，填充数据
            if (!handler.getParamterMapping().containsKey(param.getKey())){continue;}

            // ⽅法形参确实有该参数，找到它的索引位置，对应的把参数值放⼊paraValues
            Integer index = handler.getParamterMapping().get(param.getKey());
            paraValues[index] = value;
        }

        Integer requestIndex = handler.getParamterMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[requestIndex]=req;

        Integer responseIndex = handler.getParamterMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[responseIndex] = resp;

        try {
            handler.getMethod().invoke(handler.getController(),paraValues);
            resp.getWriter().write("result is ok!");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        if(handlerMapping.isEmpty()){return null;}
        String url = req.getRequestURI();

        for (Handler handler:handlerMapping){
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()){continue;}
            return handler;
        }
        return null;
    }
}
